// packageE/community/community.js
var location = require("../../../mybehaviors/location/location");
var app = getApp();
Component({
  options: {
    styleIsolation: 'shared',
  },
  behaviors: [location],
  properties: {
    datas: {
      type: null,
    },
    component_id: {
      type: null,
    },
    U_tabcontrol: {
      type: null,
    },
    btnFlag: {
      type: null
    },
    bottomShowBolIndex: {
      type: null,
    },
    index: {
      type: null,
    },
    store_id: {
      type: null,
    },
    plugin_active: {
      // 会员中心商品加载
      type: null,
    },
    store_alone_temp: {
      // 门店独立判断
      type: null,
    },
    page_id: {
      type: null,
    },
    bottomShowBol: {
      type: null,
    },
    isLast: {
      type: null,
    }
  },
  // 私有数据，可用于模板渲染
  data: {
    totalUnreadMessageCount: 0,
    emptyImage: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/image.png",
    clientWidth: "375",
    language: "",
    show_template: "", //微社区模板
    active: 1,
    cate: [
      {
        name: '关注',
        id: -2
      },
      {
        name: '发现',
        id: -3
      },
    ],
    cateList: [],
    newClassification: "",
    nearbyClassification: "",
    address: "",
    city: "",
    point: "",

    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    getMoreDataType: "newClassification",
    cateMoreData: {},
    loading: false,

    per_page: 12,
    alreadyHandleArray: [],
    arrIndex: 1,
    allLoaded: false, // 全部数据已经加载完成
    loadTab: false,
    active_secondary: 0,
    showTabs: true,
    tabNames: [

    ],
    showpopup: false,
    seachValue: '',
    timer: null,
    timerNumber: 0,
    // 设置地址
    setAddressShow: false,
    areaOptions: [],
    areaShow: false,
    addressValue: {},
    addressText: ''
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en
      });
    },
    moved() { },
    detached() { },
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() { },
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    this.getMessageTotal();
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth
    });

    if (this.data.U_tabcontrol) {
      if (Number(this.data.datas.get_number) > 0) {
        this.getFirstData(this.data.datas.list);
      }
    } else if (this.data.datas.get_style == 2) {
      this.setData({
        cateList: this.data.datas.list,
        isLoadMore: false,
        allLoaded: true,
      });
    } else {
      // if (this.data.datas.show_nearby) {
      //   this._getLocation();
      //   this.data.cate.push({
      //     name: '附近',
      //     id: -1
      //   });
      // }
      this.getHomePageData(this.data.datas.cate);
      if (Number(this.data.datas.get_number) > 0) {
        this.getFirstData(this.data.datas.list);
      }
    }
    if (this.data.datas.show_template) {
      this.setData({
        show_template: this.data.datas.show_template
      });
    }
    if (this.data.datas.list.micro_style_type == "1") {
      this.setData({
        show_template: "2"
      });
    }
    if (this.data.datas.list.micro_style_type == "0") {
      this.setData({
        show_template: "1"
      });
    }
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {
      let totalUnreadMessageCount = app.globalData.TUIKit ? app.globalData.TUIKit.getTotalUnreadMessageCount() : 0
      this.setData({
        totalUnreadMessageCount: typeof totalUnreadMessageCount === 'number' ? totalUnreadMessageCount : 0
      });
    },
    hide() { },
    resize() { },
  },
  methods: {
    getMessageTotal() {
      this.setData({
        timerNumber: this.data.timerNumber + 1
      })
      let totalUnreadMessageCount = 0;
      try{
        totalUnreadMessageCount = app.globalData.TUIKit ? app.globalData.TUIKit.getTotalUnreadMessageCount() : 0
      }catch(e){}
      this.setData({
        totalUnreadMessageCount: typeof totalUnreadMessageCount === 'number' ? totalUnreadMessageCount : 0
      });
      clearInterval(this.data.timer)
      if (this.data.timerNumber < 10) {
        this.data.timer = setInterval(() => {
          this.getMessageTotal();
        }, 500)
      }

    },
    linkGroupChatList() {
      // TUI-CustomerService/pages/index
      wx.navigateTo({
        url: "/TUI-CustomerService/pages/index"
        // url:"/packageG/pages/member/plamTravel/plamTravel"
      });
    },
    inputChange(e) {
      this.setData({
        seachValue: e.detail,
        cateList: []
      })
      this.getClassification()
    },
    inputSearch(e) {
      this.setData({
        seachValue: e.detail,
        cateList: []
      })
      this.getClassification()
    },
    clickclassflytag(e) {
      console.log(e)
      // let id = e.currentTarget.dataset.id
      let index = e.currentTarget.dataset.index
      this.setData({
        active_secondary: index,
        showpopup: false
      })
      this.getClassification()
    },
    showPopup() {
      this.setData({
        showpopup: true
      });
    },
    onClose() {
      this.setData({
        showpopup: false
      });
    },
    /**
    * 获取省市列表(区域)
    */
    getAddress: function(address = false) {
      const _this = this
      let urlStr = app.getNetAddresss("member.member-address.address");
      app._postNetWork({
        url: urlStr,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            const thirdLevelRegion = resData.data.province.map(item => {
              const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
                const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                  return {
                    text: item2.areaname,
                    value: item2.id + ''
                  }
                })
                return {
                  text: item1.areaname,
                  value: item1.id + '',
                  children: child2
                }
              })
              return {
                text: item.areaname,
                value: item.id + '',
                children: child
              }
            })
            _this.setAddress(address)
            _this.setData({
              areaOptions: thirdLevelRegion,
              setAddressShow: true
            })
          } else {
            app.tips(resData.msg)
          }
        }
      })
    },

    /**
     * 设置地址
     * @param {Object} address 地址数据
     */
    setAddress: function(address = false) {
      if (!address) return
      const { adcode, province, city, district} = address.ad_info
      this.setData({
        addressValue: {
          province_id: adcode.substr(0, 2) + '0000',
          province,
          city_id: adcode.substr(0, 4) + '00',
          city,
          district_id: adcode,
          district
        },
        addressText: [province, city, district].join('/')
      })
    },

    /**
     * 显示
     */
    toggleArea: function(e) {
      const { toggle } = e.currentTarget.dataset
      this.setData({ areaShow: toggle })
    },

    /**
     * 注册区域选中
     * @param {Object} e 
     */
    areaFinish: function(e) {
      const { selectedOptions } = e.detail
      this.setData({
        addressValue: {
          province_id: selectedOptions[0].value,
          province: selectedOptions[0].text,
          city_id: selectedOptions[1].value,
          city: selectedOptions[1].text,
          district_id: selectedOptions[2].value,
          district: selectedOptions[2].text
        },
        addressText: [selectedOptions[0].text, selectedOptions[1].text, selectedOptions[2].text].join('/'),
        areaShow: false
      })
    },

    /**
     * 获取定位
     */
    getCurrentAddress: function() {
      const _this = this
      wx.getSetting({
        success: function(settingdata) {
          // 已允许获取位置信息
          if (settingdata.authSetting['scope.userLocation']) {
            _this._getLocation((res) => {
              _this.setAddress(res)
            })
          } else {
            // 用户设置拒绝获取用户信息，打开设置
            wx.openSetting({
              success: function(settingdata) {
                if (settingdata.authSetting["scope.userLocation"]) {
                  _this._getLocation((res) => {
                    _this.setAddress(res)
                  })
                } else {
                  app.tips('请允许小程序获取您的位置信息！')
                }
              },
              fail: function(err){
                console.log(err)
              }
            })
          }
        },
        fail: function() {
          app.tips('获取用户设置信息失败！')
        }
      })
    },

    /**
     * 提交注册地址
     */
    submitAddress: function() {
      const { addressValue } = this.data
      if (!addressValue.district_id) {
        app.tips('请选择注册地址！')
        return
      }
      const _this = this
      const urlStr = app.getNetAddresss('member.address.updateAddress')
      wx.showLoading({ title: '加载中...' })
      app._postNetWork({
        url: urlStr,
        data: addressValue,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            _this.setData({
              setAddressShow: false
            })
            app.tips('保存成功！')
          } else {
            app.tips(resData.msg || '保存失败！')
          }
        },
        compolete: function() {
          wx.hideLoading()
        }
      })
    },

    /**
     * 验证用户是否存在注册地址
     * @param {Object} address 地址数据
     */
    isExistAddress: function(address = false) {
      const urlStr = app.getNetAddresss('member.address.isExistAddress')
      const _this = this
      app._getNetWork({
        url: urlStr,
        success: function(res) {
          const resData = res.data
          if (resData.result) {
            const isExist = resData.data
            if (!isExist) {
              // 获取省市县option后显示地址弹窗
              _this.getAddress(address)
            }
          } else {
            app.tips(resData.msg || '验证用户地址失败！')
          }
        }
      })
    },
    getHomePageData(data) {
      let that = this;
      // let cate = this.data.cate.concat(data);
      console.log(data, '---------data')
      this.setData({
        tabNames: data
      })
      console.log(this.data.tabNames, '---------data')
      let cate = this.data.cate
      if (this.data.datas.show_nearby) {
        // this._getLocation((res) => {
        //   this.isExistAddress(res)
        // },
        // (err) => {
        //   this.isExistAddress(err)
        // });
        cate.push({
          name: '附近',
          id: -1
        });
      }
      that.setData({
        cate: cate,
        loadTab: true
      });
    },
    getFirstData(data) {
      if (data) {
        this.setData({
          total_page: data.last_page,
        });

        if (this.data.page < this.data.total_page) {
          this.setData({
            isLoadMore: true,
          });
        } else {
          this.setData({
            isLoadMore: false,
            allLoaded: true
          });
        }

        if (data.data.length > this.data.datas.get_number) {
          data.data.splice(
            this.data.datas.get_number,
            data.data.length - this.data.datas.get_number
          );
          this.setData({
            isLoadMore: false,
            allLoaded: true
          });
        }

        this.setData({
          cateList: data.data,
        });
      }
    },
    getClassification(type, id, index) {
      let that = this;
      let urlStr = app.getNetAddresss(
        "plugin.micro-communities.api.index.getStick"
      );
      that.pageInit();
      let dataJson = {};
      if (Number(this.data.cate[this.data.active].id) > 0) {
        dataJson.cat_id = Number(this.data.cate[this.data.active].id);
      } else {
        if (Number(this.data.cate[this.data.active].id) == -3) {
          if (this.data.tabNames.length != 0) {
            dataJson.cat_id = Number(this.data.tabNames[this.data.active_secondary].id);
          }
        } else if (Number(this.data.cate[this.data.active].id) == -2) {
          dataJson.is_follow = 1;
        } else if (Number(this.data.cate[this.data.active].id) == -1) {
          dataJson.lng = this.data.point.lng;
          dataJson.lat = this.data.point.lat;
          dataJson.city_name = this.data.city;
          dataJson.address = this.data.city;
        }
      }

      if (this.data.store_id) {
        dataJson.store_id = this.data.store_id;
      }
      dataJson['keyword'] = this.data.seachValue
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: dataJson,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.data.total_page = res.data.last_page;
            // let show_template = res.data.micro_style_type == 0 ? "1" : "2";
            // this.setData({
            //   show_template
            // })
            console.log('show_template===========', this.data.show_template)
            if (res.data.data.length > this.data.datas.get_number) {
              res.data.data.splice(
                this.data.datas.get_number,
                res.data.data.length - this.data.datas.get_number
              );
              this.setData({
                isLoadMore: false,
                allLoaded: true
              });
            }

            that.setData({
              cateList: res.data.data,
            });


            if (that.data.page < that.data.total_page) {
              that.setData({
                isLoadMore: true,
                allLoaded: false
              });
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) { },
      });
    },
    getClassificationBtn(e) {
      let index = e.detail.index;
      let title = e.detail.title;
      this.setData({
        active_secondary: 0
      });
      if (e.detail.title === '发现') {
        this.setData({
          showTabs: true
        });
      } else {
        this.setData({
          showTabs: false
        });
      }
      let kongArr = []
      this.setData({
        active: index,
        cateList: kongArr
      });
      this.getClassification();
    },
    onClickSecondary(e) {
      let index = e.detail.index;
      let kongArr = []
      this.setData({
        active_secondary: index,
        cateList: kongArr
      });
      this.getClassification();
    },
    pageInit() {
      this.setData({
        page: 1,
        total_page: 0,
        isLoadMore: false,
        loading: false,
        allLoaded: true,
      });
    },
    jumpDetails(e) {
      let stick_id = e.currentTarget.dataset.stickid;
      wx.navigateTo({
        url: "/packageC/micro_communities/microCommentDetails/microCommentDetails?stickId=" +
          stick_id,
      });
    },
    getMoreData() {
      const that = this;
      if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length >= this.data.per_page) {
        that.setData({
          cateList: this.data.cateList.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
          arrIndex: this.data.arrIndex + 1
        });

        if (this.data.datas.get_number && this.data.cateList.length > this.data.datas.get_number) {
          this.setData({
            isLoadMore: false,
            allLoaded: true,
            cateList: this.data.cateList.slice(0, this.data.datas.get_number)
          });
        }
        return;
      }
      this.setData({
        isLoadMore: false,
      });
      if (that.data.page >= that.data.total_page) {
        if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0) {
          that.setData({
            cateList: this.data.cateList.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
            arrIndex: this.data.arrIndex + 1
          });
        }

        if (this.data.datas.get_number && this.data.cateList.length > this.data.datas.get_number) {
          this.setData({
            cateList: this.data.cateList.slice(0, this.data.datas.get_number)
          });
        }
        return
      }


      let json = {};
      if (Number(this.data.cate[this.data.active].id) == -2) {
        json.is_follow = 1;
      } else if (Number(this.data.cate[this.data.active].id) == -1) {
        json.lng = this.data.point.lng;
        json.lat = this.data.point.lat;
        json.city_name = this.data.city;
        json.address = this.data.city;
      } else if (Number(this.data.cate[this.data.active].id) == -3) {
        if (this.data.tabNames.length != 0) {
          json.cat_id = Number(this.data.tabNames[this.data.active_secondary].id);
        }
      } else {
        json.cat_id = Number(this.data.cate[this.data.active].id);
      }
      if (this.data.store_id) {
        json.store_id = this.data.store_id;
      }
      this.setData({
        isLoadMore: false,
      }); // 防止多次请求分页数据
      let urlStr = app.getNetAddresss(
        "plugin.micro-communities.api.index.getStick"
      );
      if (this.data.store_alone_temp == 1) {
        // 门店独立
        urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.member.nav-data");
        urlStr += '&code=' + that.data.plugin_active;
      }
      that.data.page = this.data.page + 1;
      json.page = this.data.page;
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            var myData = res.data.data;

            if (that.data.page < that.data.total_page) {
              that.setData({
                isLoadMore: true,
              });
            }
            if (myData.length > that.data.datas.get_number) {
              myData.splice(
                that.data.datas.get_number,
                myData.length - that.data.datas.get_number
              );
              this.setData({
                isLoadMore: false,
              });
            }

            that.setData({
              cateList: that.data.cateList.concat(myData),
            });

            that.triggerEvent("setLoadMore", {
              isLoadMore: that.data.isLoadMore,
            });
          } else {
            that.data.page = that.data.page - 1;
            this.setData({
              isLoadMore: false,
            });
          }
        },
        fail: function (res) { },
      });

    },
  },
  observers: {
    bottomShowBol: function (flag) {

      if (this.data.U_tabcontrol) {
        // 选项卡this.isLast判断商品列表是最后一个组件
        if (flag && this.data.isLast && this.data.isLoadMore) {
          this.getMoreData();
        } else if (this.data.page >= this.data.total_page) {
          if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0) {
            this.setData({
              newClassification: this.data.newClassification.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
              arrIndex: this.data.arrIndex + 1
            });
          }
        }
      } else {
        if (flag && this.data.bottomShowBolIndex == this.data.index && this.data.isLoadMore) {
          this.getMoreData();
        } else if (this.data.page >= this.data.total_page) {
          if (this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex).length > 0) {
            this.setData({
              newClassification: this.data.newClassification.concat(this.data.alreadyHandleArray.slice(this.data.per_page * this.data.arrIndex, this.data.per_page * (this.data.arrIndex + 1))),
              arrIndex: this.data.arrIndex + 1
            });
          }
        }
      }
    },
  },
});